<template>
  <div class="sidebar-container">
    <el-button type="danger" @click="batchDele">批量删除</el-button>
    <el-tree ref="tree" :data="data" :props="defaultProps" @node-click="handleNodeClick" show-checkbox node-key="catId"
      :expand-on-click-node="false" :default-expanded-keys="this.defaultExpanded" draggable :allow-drop="allowDrop"
      @node-drop="handleDrop">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" size="mini" v-if="data.catLevel <= 2" @click="() => append(data)">
            Append
          </el-button>
          <el-button type="text" size="mini" v-if="node.childNodes.length == 0" @click="() => remove(node, data)">
            Delete
          </el-button>
          <el-button type="text" size="mini" @click="() => edit(data)">
            Edit
          </el-button>
        </span>


      </span>
    </el-tree>

    <!-- 新增分类的对话框 -->
    <el-dialog :title="this.categoryform.catId ? `编辑分类` : `新增分类`" :visible.sync="dialogVisible" width="30%">
      <el-form ref="form" :model="categoryform" label-width="80px">
        <el-form-item label="分类名称">
          <el-input v-model="categoryform.name"></el-input>
        </el-form-item>
        <el-form-item label="分类排序">
          <el-input v-model="categoryform.sort"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button v-if="!this.categoryform.catId" type="primary" @click="appendConfirm(data)">确 定</el-button>
        <el-button v-if="this.categoryform.catId" type="primary" @click="editConfirm(data)">确 定</el-button>
      </span>
    </el-dialog>




  </div>

</template>

<script>
import { forEach } from 'lodash'
import { sort } from 'semver'

export default {
  data() {
    return {
      currentNodeMaxDeep: 0, //记录当前节点的最大深度
      data: [],
      defaultProps: {
        children: 'children',
        label: 'name',
      },
      defaultExpanded: [], //展开的节点id
      dialogVisible: false,
      categoryform: {
        catId: null,
        name: "",
        sort: "",
        parentCid: null,
        catLevel: null
      },
      // categoryform: {
      //   name: "",
      //   sort: ""
      // }, //新增分类的表单数据
    }
  },
  methods: {
    resetForm() {
      this.categoryform = {
        catId: null,
        name: "",
        sort: "",
        parentCid: null,
        catLevel: null
      };
    },
    handleNodeClick(data) {

    },
    fetchTreeData() { //请求分类数据
      this.$http({
        url: this.$http.adornUrl('/product/category/list/tree'),
        method: 'get'
      }).then(({ data }) => {
        console.log(data)
        this.data = data.page
      })
    },
    edit(data) {
      //修改三级分类
      // this.categoryform = {};
      this.resetForm()
      this.categoryform.catId = data.catId
      this.categoryform.name = data.name
      this.categoryform.sort = data.sort
      this.defaultExpanded = [data.catId]
      this.dialogVisible = true
    },
    editConfirm() {
      this.dialogVisible = false
      this.$http({
        url: this.$http.adornUrl('/product/category/update'),
        method: 'post',
        data: this.$http.adornData(
          this.categoryform, false
        )
      }).then(({ data }) => {
        if (data.code == 0) {
          this.$message({
            message: '修改成功',
            type: 'success'
          });
          this.fetchTreeData()
        } else {
          this.$message.error('修改失败');
        }
      }).catch(() => {

      })


    },
    append(data) {
      this.resetForm()
      // this.categoryform = {}
      this.categoryform.parentCid = data.catId
      this.categoryform.catLevel = data.catLevel * 1 + 1
      this.defaultExpanded = [data.catId]
      this.dialogVisible = true
    },
    appendConfirm() {
      this.dialogVisible = false
      this.$http({
        url: this.$http.adornUrl('/product/category/save'),
        method: 'post',
        data: this.$http.adornData(
          this.categoryform, false
        )
      }).then(({ data }) => {
        if (data.code == 0) {
          this.$message({
            message: '新增成功',
            type: 'success'
          });
          this.fetchTreeData()
        } else {
          this.$message.error('新增失败');
        }
      }).catch(() => {

      })


    },
    remove(node, data) {  //删除分类数据
      this.$confirm('是否删除菜单【data.name】?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //确认删除，发送请求
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(
            [data.catId], false
          )
        }).then(({ data }) => {
          if (data.code == 0) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.fetchTreeData()
            this.defaultExpanded = [node.parent.data.catId]
          } else {
            this.$message.error('删除失败');
          }
        })
      }).catch(() => {

      })




    },
    allowDrop(draggingNode, dropNode, type) { //判断是否能拖动到对应节点，需要判断当前节点的最大深度加上父节点的深度是否小于等于3
      //获取当前节点的最大深度
      this.currentNodeMaxDeep = 0
      this.getMaxDeep(draggingNode)

      //计算层级
      var parentLevel
      if (type == "inner") { //如果是inner 父节点就是要移入的节点
        parentLevel = dropNode.level
      } else {  //如果是前或者后，父节点就是要移入节点的父节点
        parentLevel = dropNode.parent.level
      }
      if ((this.currentNodeMaxDeep + 1 - draggingNode.level + parentLevel) <= 3) {
        return true
      }
      return false;
    },
    getMaxDeep(draggingNode) { //计算指定节点的最大深度
      for (let index = 0; index < draggingNode.childNodes.length; index++) {
        if (draggingNode.childNodes[index].level > this.currentNodeMaxDeep) {
          this.currentNodeMaxDeep = draggingNode.childNodes[index].level
        }
        this.getMaxDeep(draggingNode.childNodes[index])
      }
      return this.currentNodeMaxDeep
    },
    handleDrop(draggingNode, dropNode, dropType, ev) {   //完成拖拽后保存到数据库
      let parentCid = 0;
      let level = 0;
      let broList = []
      let updateNodeList = []
      let levelChanged = false  //记录层级是否变化

      if (dropType == "inner") {
        //获取父id
        parentCid = dropNode.data.catId
        //获取兄弟节点列表
        broList = dropNode.childNodes
        //获取层级
        level = dropNode.data.catLevel * 1 + 1

      } else {
        //获取父id
        parentCid = dropNode.data.parentCid
        //获取兄弟节点列表
        broList = dropNode.parent.childNodes
        //获取层级
        level = dropNode.data.catLevel
      }
      //遍历所有的兄弟节点，其中也包含了当前节点
      for (let index = 0; index < broList.length; index++) {
        if (broList[index].data.catId == draggingNode.data.catId) {
          updateNodeList.push({ catId: broList[index].data.catId, sort: index, parentCid: parentCid, catLevel: level })
          if (draggingNode.level != level) {
            levelChanged = true
          }
          continue
        }
        updateNodeList.push({ catId: broList[index].data.catId, sort: index })
      }
      let childNodesUpdate = []
      //修改层级
      if (levelChanged) {
        draggingNode.data.catLevel = level
        this.nodeLevelChange(draggingNode, childNodesUpdate)
      }
      if (levelChanged.length != 0) {
        updateNodeList.push(...childNodesUpdate)
      }
      console.log("需要更新的节点列表", updateNodeList)
      //发送更新请求
      this.$http({
        url: this.$http.adornUrl('/product/category/batchUpdate'),
        method: 'post',
        data: this.$http.adornData(
          updateNodeList, false
        )
      }).then(({ data }) => {
        if (data.code == 0) {
          this.$message({
            message: '菜单顺序修改成功',
            type: 'success'
          });
          this.fetchTreeData()
          this.defaultExpanded = [parentCid]

        } else {
          this.$message.error('菜单顺序修改失败');
        }
      }).catch(() => {

      })


    },
    nodeLevelChange(node, result) { //修改节点下所有子节点的层级
      let children = node.childNodes
      children.forEach(element => {
        element.data.catLevel = node.data.catLevel * 1 + 1
        result.push({ catId: element.data.catId, catLevel: element.data.catLevel })
        this.nodeLevelChange(element)
      });
    },
    batchDele() { //批量删除
      let checkNodes = this.$refs.tree.getCheckedKeys()
      console.log(checkNodes)

      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        //确认删除，发送请求
        this.$http({
          url: this.$http.adornUrl('/product/category/delete'),
          method: 'post',
          data: this.$http.adornData(
            checkNodes, false
          )
        }).then(({ data }) => {
          if (data.code == 0) {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.fetchTreeData()
            this.defaultExpanded = [node.parent.data.catId]
          } else {
            this.$message.error('删除失败');
          }
        })
      }).catch(() => {

      })

    }


  },
  created() {
    this.fetchTreeData()
  }
}

</script>

<style scoped>
.sidebar-container {
  /* width: 350px; */
  height: 100%;
  background-color: #f5f5f5;
  border-right: 1px solid #e6e6e6;
  overflow-y: auto;
}
</style>
